﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RookieLibSharp.Configuration;
using RookieLibSharp.Progress;
using System.Threading;
using System.Runtime.InteropServices;
using System.Reflection;
using System.IO;
using RookieLibSharp.WinApi;
using BirthdayRemainder.Model;
using RookieLibSharp.Security;
using System.Diagnostics;

namespace BirthdayRemainder
{
    public partial class FrmMain : Form
    {
        SftMgr sftMgr;
        ListViewOperate LstOp;
        public FrmMain()
        {
            InitializeComponent();
        }

#region 窗体相关

        private void FrmMain_Load(object sender, EventArgs e)
        {
            LstOp = new ListViewOperate(LstView);
            LstOp.SortColumn = 4;
            InitFrm();
        }
        /// <summary>
        /// 消息处理
        /// </summary>
        /// <param name="m"></param>
        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case (int)WM_MSG.WM_MSG_HAS_UPDATE:
                    this.menuHasNewVersion.Visible = Cfg.ReadBool(GlobalValue.SFT_CFG,GlobalValue.SFT_CFG_HAS_NEW_VERSION,false);
                    break;
                case (int)WM_MSG.WM_MSG_LIST_INIT:
                    ProgressManager.StartThread(InitLstView);
                    break;
                case (int)WM_MSG.WM_MSG_LIST_ADD_ITEM:
                    StPersonInfo info = new StPersonInfo();
                    info = (StPersonInfo)m.GetLParam(info.GetType());
                    LstOp.AddItem(LstOp.Convert2ListViewItem(info));
                    break;
                case (int)WM_MSG.WM_MSG_SHOW_MSG:

                    break;
                default:
                    break;
            }
            base.WndProc(ref m);
        }
        //窗体关闭
        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            SaveCfg();
            sftMgr.Abort();
        }
        /// <summary>
        /// 初始化窗体
        /// </summary>
        private void InitFrm()
        {
            sftMgr = new SftMgr(this.Handle);
            SetFrmProperty();
            LoadCfg();
            sftMgr.RunBackgroundProc();
        }
        /// <summary>
        /// 日历控件初始化
        /// XP系统下不显示日历
        /// </summary>
        private void DisplayMonthCalendar()
        {
            System.OperatingSystem osInfo = System.Environment.OSVersion;
            if ((osInfo.Platform == PlatformID.Win32NT) && (osInfo.Version.Major == 5))
            {
                this.mthCalendar.Visible = false;
            }
        }
        /// <summary>
        /// 设置窗体属性
        /// </summary>
        /// <param name="icon">图标</param>
        /// <param name="title">标题</param>
        /// <param name="version">版本号</param>
        private void SetFrmProperty()
        {
            this.Icon = BirthdayRemainder.Properties.Resources.ico_main;
            this.Text = "生日提醒 V" + Funcs.GetSftVersion();
            this.notifyIcon.Icon = this.Icon;
            this.menuHasNewVersion.Visible = false;
            DisplayMonthCalendar();
        }

        private void LoadCfg()
        {
            
            Cfg.SetCfgPath(GlobalValue.SftwareDataDir + GlobalValue.SFT_CFG_FILE_NAME);
            if (!sftMgr.CfgFileNameExist())
            {
                Funcs.runWhenStart(true, Application.ExecutablePath);
                Cfg.WriteConfig(GlobalValue.SFT_CFG, GlobalValue.SFT_CFG_RUN_POWER_ON, true);
            }

            if (Cfg.ReadBool(GlobalValue.SFT_CFG, GlobalValue.SFT_CFG_BR, true))
            {
                string BRExtention = Path.GetDirectoryName(Application.ExecutablePath) + "\\" + GlobalValue.EXTENTION_APP;
                Funcs.RunApp(BRExtention, GlobalValue.EXTENTION_APP);
            }
        }
        private void SaveCfg()
        {
            
        }
#endregion

#region 菜单
        //文件-导入数据
        private void menuFileImportInfo_Click(object sender, EventArgs e)
        {
            RegCheck();
            if (sftMgr.ShowImportData())
            {
                sftMgr.InitLstView();
            }
        }
        //文件-导出数据
        private void menuFileExportInfo_Click(object sender, EventArgs e)
        {
            RegCheck();
            sftMgr.ShowExportData();
        }
        //设置
        private void menuSet_Click(object sender, EventArgs e)
        {
            SetReturn setRet = sftMgr.ShowSet();
            if (setRet.RefreshList)
            {
                LstOp.InitLstView();
            }
            if (setRet.RefreshBackColor)
            {
                LstOp.SetBackColor();
            }
        }
        //帮助-意见建议
        private void menuHelpAdvice_Click(object sender, EventArgs e)
        {
            sftMgr.ShowHelpAdvice();
        }
        //帮助-关于作者
        private void menuHelpAbout_Click(object sender, EventArgs e)
        {
            Msg(sftMgr.GetAboutMe());
        }

        //help - register the software
        private void menuHelpRegister_Click(object sender, EventArgs e)
        {
            sftMgr.ShowRegForm();
        }
        //help - open taobao item page
        private void menuHelpPurchase_Click(object sender, EventArgs e)
        {
            Process.Start(GlobalValue.SOFT_PURCHASE_URL);
        }
        //help - check update
        private void menuHelpCheckUpdate_Click(object sender, EventArgs e)
        {

            if (!Funcs.CheckNetConnection())
            {
                Msg("检测网络连接");
                return;
            }

            SoftwareUpdateInfor updateInfo = sftMgr.CheckUpdate(true);
            
            if (updateInfo.NeedUpdate)
            {
                string str = string.Format("当前版本:V{0}\r\n升级版本:V{1}\r\n\r\n是否打开升级网址?", updateInfo.CurrentVersion, updateInfo.UpdateVersion);
                if (Msg(str, MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    Process.Start(updateInfo.UpdateUrl);
                    sftMgr.SetDisHasNewVersion(false);
                }
            }
            else
            {
                Msg("该软件已经为最新");
            }
        }
        //help - open home page
        private void menuHelpHomePage_Click(object sender, EventArgs e)
        {
            GlobalValue.sftReg.ShowHomePage();
        }
        //new version
        private void menuHasNewVersion_Click(object sender, EventArgs e)
        {
            if (GlobalValue.SftwareDownloadUrl != "")
            {
                Process.Start(GlobalValue.SftwareDownloadUrl);
            }
            sftMgr.SetDisHasNewVersion(false);
        }
        //notify
        private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left)
            {
                return;
            }
            if (!this.Visible)
            {
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
                this.notifyIcon.Visible = false;
            }
        }
#endregion

#region 列表操作
        /// <summary>
        /// 初始化显示列表
        /// </summary>
        private void InitLstView()
        {
            int itemCnt = LstOp.InitLstView();
            if (itemCnt > 0)
            {
                DisplayInfo(LstOp.GetItem(0));
            }
            else
            {
                DisplayInfo(null);
            }
            //LstOp.Sort();
        }
        //单击显示内容
        private void LstViewInfo_Click(object sender, EventArgs e)
        {
            ListViewItem item = LstOp.GetSelectedItem(0);
            if (item != null)
            {
                DisplayInfo(item);
            }
        }
        //添加信息
        private void CMLstAddInfo_Click(object sender, EventArgs e)
        {
            RegCheck();
            sftMgr.ShowAddInfo();
        }
        //修改信息
        private void CMLstModify_Click(object sender, EventArgs e)
        {
            RegCheck();
            ListViewItem item = LstOp.GetSelectedItem(0);
            if (item == null)
            {
                Msg("先选中一行，再修改");
                return;
            }
            string modiyName =  sftMgr.ShowModify(item.SubItems[1].Text);
            PersonInfo info = SftMgr.DbGetRecord(modiyName);
            item.SubItems[1].Text = info.Name;
            item.SubItems[2].Text = info.Birthday;
            item.SubItems[3].Text = info.SolorOrLunar;
            item.SubItems[4].Text = info.DayToBirthday.ToString();
            item.SubItems[5].Text = info.Phone;
            LstOp.SetLstViewItemBackColor(item, info.DisplayBackColor);
            LstOp.Sort();
        }
        //删除信息
        private void CMLstDelete_Click(object sender, EventArgs e)
        {
            RegCheck();
            if (LstOp.GetCheckedItemsCount() == 0)
            {
                Msg("先选中，再删除");
                return;
            }
            if (0 == LstOp.DeleteSelectedItems())
            {
                DisplayInfo(null);
            }
            
        }

#endregion

        private delegate DialogResult dl_Msg(string str, MessageBoxButtons btn);
        /// <summary>
        /// 消息显示
        /// </summary>
        /// <param name="str">消息内容</param>
        /// <param name="btn">按钮类型</param>
        /// <returns>消息窗体结果</returns>
        private DialogResult Msg(string str, MessageBoxButtons btn = MessageBoxButtons.OK)
        {
            if (this.InvokeRequired)
            {
                dl_Msg method = Msg;
                return (DialogResult)Invoke(method, str, btn);
            }
            return MessageBox.Show(str, "提醒", btn);
        }

        private delegate void dl_CloseFrm();
        /// <summary>
        /// 关闭窗口
        /// </summary>
        private void CloseFrm()
        {
            if (this.InvokeRequired)
            {
                dl_CloseFrm method = CloseFrm;
                Invoke(method);
            }
            else
            {
                this.Close();
            }
        }
        private delegate void dg_DisplayInfo(ListViewItem item);
        /// <summary>
        /// 显示信息
        /// </summary>
        /// <param name="item"></param>
        private void DisplayInfo(ListViewItem item)
        {
            if (this.InvokeRequired)
            {
                dg_DisplayInfo method = DisplayInfo;
                Invoke(method, item);
            }
            else
            {
                if (item == null)
                {
                    this.tbName.Text = "";
                    this.tbBirthday.Text = "";
                    this.tbSolarLunar.Text = "";
                    this.tbPhone.Text = "";
                }
                else
                {
                    this.tbName.Text = item.SubItems[1].Text;
                    this.tbBirthday.Text = item.SubItems[2].Text;
                    this.tbSolarLunar.Text = item.SubItems[3].Text;
                    this.tbPhone.Text = item.SubItems[5].Text;
                }
            }
        }


        private void tTimer_Tick(object sender, EventArgs e)
        {
            string str = Funcs.GetLunarStr(DateTime.Today) + DateTime.Now.ToString(" HH:mm:ss");
            this.LabDate.Text = str;
        }
        private void RegCheck()
        {
            if (GlobalValue.regRsult == RegisterResult.FAILED)
            {
                Msg("功能受限，请注册");
            }
        }
    }
}
